import { Button, DataGrid, Popup, SelectBox, TextBox } from "devextreme-react";
import { useModel } from "umi";
import { DevToolBar, CpasIcon, DevGrid, DevPopup } from '~/public/cpas-ui';
import React, { useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react"
import Toolbar, { Item } from 'devextreme-react/toolbar';
import { intl } from "@/utils";
import { CFLKMConfigDelete, CFLKMConfigUpdate, getCFLKMConfigDataList } from "../service"
import { Popover } from "antd";
import CarryEntryPopup from "~/public/cpas-business/components-bs/CarryEntryPopup";
import notify from "devextreme/ui/notify";


const SetReclassiFiedItem: React.FC<any> = React.forwardRef((props: any, ref) => {
    const { initialState } = useModel('@@initialState');
    const { dbname } = initialState?.curPart as API.CurPart;
    const { username } = initialState?.curUser as API.CurUser;
    const { width, height, DataId } = props

    const Data_ID = useRef<any>();
    const DelteRef = useRef<any>();
    const diaParams = useRef<any>();
    const devGridRef = useRef<any>();
    const carryEntryRef = useRef<any>();
    const JFKMBHRef = useRef<any>();
    const DFKMBHRef = useRef<any>();

    const [data, SetData] = useState<any[]>([])
    const [index, setIndex] = useState<string>('')
    const [visible, setVisible] = useState<boolean>(false);
    const [size, setSize] = useState<any>({ width, height });

    const fetchData = async () => {
        const r = await getCFLKMConfigDataList({
            dbname,
            Data_ID: DataId
        })
        SetData(r);
    };

    useImperativeHandle(ref, () => ({
        show: async (params: any) => {
            await fetchData();
            diaParams.current = params;
            Data_ID.current = DataId
            setVisible(true);

        },
    }))

    // 点击关闭按钮逻辑
    const onHiding = () => {
        setVisible(false)
    }

    const columns = [
        {
            dataField: "JFKMMC",
            dataType: "string",
            caption: "借方科目",
            // width: 130,
            alignment: "left",
            allowEditing: false,
            allowUpdating: false,
            cellRender: (cell: any) => {
                // JFKMBHRef.current = r.row.data.KMBH;
                return <div style={{ display: 'flex', justifyContent: ' space-between' }}>
                    <div>
                        {cell.data.JFKMMC}
                    </div>
                    <div>
                        <CpasIcon type='icon-ellipsis' onClick={() => {
                            carryEntryRef.current.show({
                                dbname,
                                Data_ID: Data_ID.current,
                                // 是否显示总账
                                isHasFZZ: false,
                                editUser: username,
                                selectMode: "0",
                                // 选择 模式 0：单选 1：多选连机选择
                                auxiliaryState: true,
                                isSelectSuperior: true,
                                // 是否为辅助帐
                                okCallback: async (r: any) => {
                                    JFKMBHRef.current = r.row.data.KMBH;
                                    devGridRef.current.instance.cellValue(cell.rowIndex, 'JFKMMC', r.row ? r.row.data.name : r.name);
                                    await CFLKMConfigUpdate({
                                        dbname,
                                        Data_ID: Data_ID.current,
                                        GUID: cell.key,
                                        JFKMBH: r.row ? r.row.data.KMBH : r.KMBH,
                                        DFKMBH: cell.data.DFKMBH === undefined ? DFKMBHRef.current : cell.data.DFKMBH
                                        // DFKMBH: DFKMBHRef.current ? DFKMBHRef.current : cell.data.DFKMBH ? cell.data.DFKMBH : ""
                                    })
                                },
                            })
                        }} />
                    </div>
                </div>
            }
        },
        {
            dataField: "DFKMMC",
            dataType: "string",
            caption: "贷方科目",
            // width: 130,
            alignment: "left",
            allowEditing: false,
            allowUpdating: false,
            cellRender: (cell: any) => {
                return <div style={{ display: 'flex', justifyContent: ' space-between' }}>
                    <div style={{ whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
                        {cell.data.DFKMMC}
                    </div>
                    <div>
                        <CpasIcon type='icon-ellipsis' onClick={() => {
                            carryEntryRef.current.show({
                                dbname,
                                Data_ID: Data_ID.current,
                                // 是否显示总账
                                isHasFZZ: false,
                                editUser: username,
                                selectMode: "0",
                                // 选择 模式 0：单选 1：多选连机选择
                                auxiliaryState: true,
                                isSelectSuperior: true,
                                // 是否为辅助帐
                                okCallback: async (r: any) => {
                                    console.log(r, 'r----------');
                                    console.log(cell, 'cell------');
                                    devGridRef.current.instance.cellValue(cell.rowIndex, 'DFKMMC', r.row ? r.row.data.name : r.name);
                                    DFKMBHRef.current = r.row.data.KMBH;
                                    await CFLKMConfigUpdate({
                                        dbname,
                                        Data_ID: Data_ID.current,
                                        GUID: cell.key,
                                        JFKMBH: cell.data.JFKMBH === undefined ? JFKMBHRef.current : cell.data.JFKMBH,
                                        // JFKMBH: JFKMBHRef.current !== undefined  ? JFKMBHRef.current : cell.data.JFKMBH ? cell.data.JFKMBH : "",
                                        DFKMBH: r.row ? r.row.data.KMBH : r.KMBH,
                                    })
                                },
                            })
                        }} />
                    </div>
                </div>
            }
        },
    ]
    const contents = (e: any) => {
        return <>{e}</>
    }
    const TopCellClick = (e: any) => {
        if (e.rowType !== "header") {
            // eslint-disable-next-line @typescript-eslint/no-unused-expressions
            e.rowIndex !== -1 ? setIndex(e.data.GUID) : ""
        }
        return {}
    }
    // 添加
    const AddItem = useCallback(() => {
        return <div style={{ marginTop: '3px', marginRight: '8px', marginLeft: '8px' }}>
            <span>
                <Popover content={contents("增加")} placement="top">
                    <span>
                        <CpasIcon type='icon-add-circle' fontSize={18}
                            onClick={() => {
                                devGridRef.current.instance.addRow();
                                JFKMBHRef.current = "";
                                DFKMBHRef.current = "";
                            }}
                        />
                    </span>
                </Popover>
            </span>
        </div>
    }, [])

    // 删除
    const DeleteItem = useCallback(() => {
        return <div style={{ marginTop: '3px', marginRight: '15px' }}>
            <span>
                <Popover content={contents("删除")} placement="top">
                    <CpasIcon type='icon-minus-circle' fontSize={18}
                        onClick={async () => {
                            console.log(index, 'index----');
                            if (index) {
                                DelteRef.current.show({
                                    title: "删除提醒",
                                    okCallback: async () => {
                                        const r = await CFLKMConfigDelete({
                                            dbname,
                                            GUID: index,
                                        })
                                        if (r) fetchData(), notify("删除成功", "success", 2000);
                                    }
                                });
                            } else {
                                notify("请选择您要删除的科目", "warning", 2000)
                            }
                        }}
                    />
                </Popover>
            </span>
        </div>
    }, [index])

    return (
        <div style={{ width: '100%', height: '100%' }}>
            <Popup
                width='100%'
                height="100%"
                // shading={false}
                ref={ref}
                // dragOutsideBoundary={true}
                resizeEnabled={true}
                visible={visible}
                title='设置自动重分类科目'
                minWidth={500}
                minHeight={300}
                {...props}
                {...size}
                onHiding={onHiding}
                onResizeEnd={(e) => {
                    setSize({ width: e.width, height: e.height });
                }}
                toolbarItems={[
                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'after',
                        options: {
                            text: intl('pub.cancel', '关闭'),
                            onClick: () => setVisible(false)
                        },
                    },
                    {
                        widget: 'dxButton',
                        toolbar: 'bottom',
                        location: 'after',
                        options: {
                            text: intl('pub.ok', '确定'),
                            type: 'default',
                            onClick: () => {
                                setVisible(false);
                                diaParams.current?.ok();
                            }
                        },
                    },
                ]}

            >
                <div style={{ width: '100%', height: '100%', display: 'flex', flexDirection: 'column' }}>
                    <div style={{ width: '100%', height: '12%' }}>
                        <span>借方科目出现负值或贷方余额,重分类为贷方科目； 贷方科目出现负值或者借方余额,重分类为借方科目；</span>
                    </div>
                    <div style={{ width: '100%', height: '80%' }}>
                        <Toolbar>
                            <Item location="before" render={AddItem} />
                            <Item location="before" render={DeleteItem} />
                            <Item location="before" text='默认为6大往来科目' />
                        </Toolbar>
                        {
                            useMemo(() => {
                                return <DevGrid.RangeTap
                                    ref={devGridRef}
                                    id="GUID"
                                    dataSource={data}
                                    keyExpr="GUID"
                                    columnAutoWidth={true}
                                    defaultColumns={columns}
                                    showBorders={true}
                                    showRowLines={true}
                                    showColumnLines={true}
                                    headerFilter={{ visible: false }}
                                    filterPanel={{ visible: false }}
                                    filterRow={{ visible: false }}
                                    paging={{
                                        enabled: false
                                    }}
                                    editing={{
                                        allowAdding: false,
                                        allowUpdating: false,
                                        allowDeleting: false,
                                        mode: "cell",
                                        newRowPosition: 'last'
                                    }}
                                    onCellClick={TopCellClick}
                                    onSaved={(e: any) => {
                                        console.log(e, '-------');
                                    }}
                                />
                            }, [data])
                        }
                    </div>
                </div >
            </Popup >
            <CarryEntryPopup ref={carryEntryRef} />
            <DevPopup.Default ref={DelteRef} width={80} height={220}  >
                {() => {
                    return <span>确定要执行此删除操作吗？</span>
                }}
            </DevPopup.Default>
        </div >
    )
});

export default React.memo(SetReclassiFiedItem);
